<template>
    <div>
        <el-card>
            <h3>管理上传</h3>
        </el-card>
        <el-card>
            <div>
                <el-form :inline="true" :model="Upline">
                    <el-form-item label="模型标识key:">
                        <el-date-picker v-model="dateNumber" type="daterange" start-placeholder="开始时间"
                            end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss" @change="ChangeData">
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item label="模型标识key:">
                        <el-input v-model="Upline.modelKey" placeholder="模型标识key" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="用户名:">
                        <el-input v-model="Upline.username" placeholder="用户名" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="文件状态:">
                        <el-select v-model="Upline.fileStatus" clearable placeholder="文件状态" class="GlTyCss">
                            <el-option v-for="apiky in fileStaList" :key="apiky.value" :label="apiky.label"
                                :value="apiky.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="QueryFile()">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="Resetting">重置</el-button>
                    </el-form-item>
                    <!-- <el-form-item>
                      <el-button type="info" @click="FileUploads">文件上传</el-button>
                  </el-form-item> -->
                </el-form>
            </div>
            <el-table :data="TemplateList.records" style="width: 100%">
                <el-table-column prop="createDate" label="时间" width="200">
                </el-table-column>
                <el-table-column prop="username" label="用户账号" width="120">
                </el-table-column>
                <el-table-column prop="modelKey" label="模型" width="160">
                </el-table-column>
                <el-table-column prop="taskId" label="任务ID" width="300">
                </el-table-column>
                <el-table-column prop="fileStatus" label="任务状态">
                    <template slot-scope="scope">
                        <span v-if="scope.row.fileStatus == 'UPLOAD_SUCCESS'" style="color: grey;">处理中</span>
                        <span v-if="scope.row.fileStatus == 'PROCESSING_SUCCESS'" style="color: green;">任务完成</span>

                    </template>
                </el-table-column>
                <el-table-column prop="params" label="文件内容" width="300">
                    <template slot-scope="scope">
                        <span>{{ scope.row.params }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-download" plain @click="DownFile(scope.row)"
                            size="mini">下载</el-button>
                        <el-button type="text" icon="el-icon-upload2" plain @click="FileUploads(scope.row)"
                            size="mini">上传</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :page-sizes="[10, 50, 100, 1000]" :page-size="10" layout="total, sizes, prev, pager, next, jumper"
                :total="TemplateList.total" style="margin: 20px 0;float: right;">
            </el-pagination>


            <!-- 文件上传 -->

            <el-dialog title="文件上传" :visible.sync="UpFileDialog" width="420px">
                <div>

                    <el-form :inline="true" :model="formInline" class="demo-form-inline">


                        <el-form-item label="文件">
                            <el-upload class="upload-demo" drag ref="uploadKUser" :http-request="onUploadKUser"
                                action="" :on-preview="handlePreviewKUser" :on-remove="handleRemoveKUser"
                                :file-list="fileListKUser" :on-change="handleFileChange" :on-success="uploadSuccess"
                                :multiple="true" :auto-upload="false" accept="" :limit="50" :on-exceed="OnExceedKUser">
                                <i class="el-icon-upload"></i>
                                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            </el-upload>
                        </el-form-item>
                    </el-form>



                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="CancelFiles">取消上传</el-button>
                    <el-button type="primary" @click="Determine">确定上传</el-button>
                </span>
            </el-dialog>

            <!-- 文还上传 -->
        </el-card>
    </div>
</template>

<script>
import { AdminUserFiles, UpUserFiles, QueryModelkey, UserUploadfile, DownFiles } from '@/api/table'
import request from '../../../../vue.config'
import JSZip from 'jszip';
export default {
    data() {
        return {
            TemplateList: [],
            UpFileDialog: false,
            Upline: {
                modelKey: '',
                username: '',
                fileStatus: '',
                endTime: '',
                beginTime: ''

            },
            dateNumber: '',
            formInline: {
                RechargeType: ""
            },
            fileStaList: [

                {
                    value: "UPLOAD_SUCCESS",
                    label: '处理中'
                },
                {
                    value: "PROCESSING_SUCCESS",
                    label: '任务完成'
                },

            ],
            pageCode: 1,
            pageSize: 10,
            fileListKUser: [],
            pageCode: 1,
            pageSize: 10,
            CsvRole: '',
            timestamp: '',
            RequestUrl: '',
            modelKey: [],
            ModelKeyOne: '',
            ZipFiles: ''
        };
    },
    created() {
        this.QueryFile()
        console.log(this.timestamp, "wenjain")
        this.CsvRole = localStorage.getItem('CsvRole');
        this.RequestUrl = request.devServer.proxy["/api"].target
        this.QueryModel()
    },
    methods: {
        async QueryModel() {
            QueryModelkey().then(res => {
                this.modelKey = res.data
                console.log(this.modelKey, "wenjain")
            })
        },
        async DownFile(row) {
            // localhost:8081/datac/business/file/download?taskId=20240712f97292a7140747e78200cc2e
            // const DownUrl = this.RequestUrl + `/datac/business/file/download?taskId=${row.taskId}`
            // console.log(DownUrl, "wenjain2222")
            // window.open(DownUrl,'_blank')
            // const DownUrl = this.RequestUrl + `/datac/business/file/download?taskId=${row.taskId}`
            // console.log(res, "wenjain")
            // window.open(DownUrl)
            //     console.log(DownUrl, "wenjain2")
            DownFiles(row.taskId).then(response => {
                const url = window.URL.createObjectURL(new Blob([response]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', 'filename.zip');
                link.click();
                window.URL.revokeObjectURL(url);
                setTimeout(() => {
                    document.body.removeChild(link);
                }, 2000);

            })



        },

        // 查询文件
        async QueryFile() {
            UserUploadfile(this.pageCode, this.pageSize, this.Upline).then(res => {
                this.TemplateList = res.data.value
            })
        },

        // 清空每一项的值
        clearObject(obj) {
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    obj[key] = '';
                }
            }
        },


        // 文件上传
        FileUploads(row) {
            this.UpFileDialog = true;
            this.ModelKeyOne = row.taskId;
            this.ModelKeyTwo = row.modelKey
        },

        async onUploadKUser(file) {
            // let taskId = this.CsvRole + `_` + this.timestamp;
            const formData = new FormData()
            formData.append("file", file.file);
            formData.append("taskId", this.ModelKeyOne);
            formData.append("modelKey", this.ModelKeyTwo);

            let UpFiles = await AdminUserFiles(formData);

            // console.log(formData,"wenjain1")
        },
        // 确定上传
        Determine() {
            this.$refs.uploadKUser.submit();
            this.UpFileDialog = false;
            this.$refs.uploadKUser.clearFiles();
            this.QueryFile()

        },
        // 取消上传清空文件
        CancelFiles() {
            this.UpFileDialog = false;
            this.$refs.uploadKUser.clearFiles();
        },
        // 点击文件列表中已上传的文件时的钩子
        handlePreviewKUser(file) {
            console.log(file, "1");
        },
        // 	文件列表移除文件时的钩子
        handleRemoveKUser(file, fileList) {
            console.log(file, fileList, "文件列表移除文件时的钩子");
            const arr = []
            for (let i = 0; i < this.fileListKUser.length; i++) {
                if (this.fileListKUser[i].uid !== file.uid) {
                    arr.push(this.fileListKUser[i])
                }
            }
            this.fileListKUser = arr
            // console.log(this.fileListKUser, "this.fileListKUser")
        },
        // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
        handleFileChange(file, fileList) {
            this.fileListKUser = fileList

            console.log(this.fileListKUser, "this.fileListKUser")


            // const zip = new JSZip();
            // function addFileIfNotExists(zip, file) {
            //     if (!zip.file(file.name)) {
            //         zip.file(file.name, file.raw);
            //         console.log(`Added file: ${file.name}`);
            //     } else {
            //         console.log(`Skipped duplicate file: ${file.name}`);
            //     }
            // }
            // this.fileListKUser.forEach(file => addFileIfNotExists(zip, file));  
           
            // zip.generateAsync({ type: "blob" })  
            //     .then(function (content) {
                   
            //         console.log(content, "4564646464");
            //         this.ZipFiles = content;
            //     });
        },
        // 上传成功
        uploadSuccess(response, file, fileList) {
            console.log('上传成功')
        },
        OnExceedKUser() {
            this.$message({
                message: "文件上传超出限制",
                type: 'error'
            });
        },


        // 重置
        Resetting() {
            this.clearObject(this.Upline)
            this.QueryFile()
        },
        // 分页


        async handleSizeChange(val) {
            this.pageSize = val;
            this.QueryFile()
        },
        async handleCurrentChange(val) {
            this.pageCode = val;
            this.QueryFile()

        },
        ChangeData(e) {
            if (e) {
                this.Upline.beginTime = e[0]
                this.Upline.endTime = e[1]
            } else {
                this.Upline.endTime = ''
                this.Upline.beginTime = ''
            }
        }
    },
};
</script>

<style lang="scss" scoped></style>